package mix

import (
	"qingbing/xzutils/utils"
	"reflect"
)

// 结构体根据 tag 转换成 map， tag 默认 json
func StructToMap(obj interface{}, tags ...string) map[string]interface{} {
	var tag string
	if len(tags) > 0 {
		tag = tags[0]
	} else {
		tag = "json"
	}

	m := make(map[string]interface{})
	val := utils.GetReflectValue(obj)
	for i := 0; i < val.NumField(); i++ {
		field := val.Type().Field(i)
		key := field.Tag.Get(tag)
		subVal := val.Field(i)
		if !subVal.CanInterface() {
			continue
		}
		if key == "" {
			if subVal.Kind() == reflect.Struct {
				// 值为结构体
				Mixins(m, StructToMap(subVal.Interface(), tag))
			} else if subVal.Kind() == reflect.Ptr && subVal.Elem().Kind() == reflect.Struct && !subVal.IsNil() {
				// 值为结构体指针
				Mixins(m, StructToMap(subVal.Interface(), tag))
			}
		} else if subVal.Kind() == reflect.Ptr {
			if !subVal.IsNil() {
				m[key] = subVal.Elem().Interface()
			}
		} else {
			m[key] = subVal.Interface()
		}
	}
	return m
}
